import {ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {MyTableConfig} from "../../share/components/ant-table/ant-table.component";
import {FileTypeObj, SearchCommonVO} from "../../core/services/types";
import {NzTableQueryParams} from "ng-zorro-antd/table";
import {ChatService} from "../../core/services/http/chat.service";
import {LabelTypeModalService} from "../../widget/biz-widget/label-type-modal/label-type-modal.service";
import {ModalBtnStatus} from "../../widget/base-modal";
import {NzModalService} from "ng-zorro-antd/modal";

interface SearchParam {
  typeName: string;
}

@Component({
  selector: 'app-label-type',
  templateUrl: './label-type.component.html',
  styleUrls: ['./label-type.component.less']
})
export class LabelTypeComponent implements OnInit {
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  tableConfig!: MyTableConfig;
  dataList!: FileTypeObj[];
  checkedCashArray: FileTypeObj[] = [];
  searchParam: Partial<SearchParam> = {};

  constructor(private dataService: ChatService, private cdr: ChangeDetectorRef, private modalService: LabelTypeModalService, private modalSrv: NzModalService) {
  }

  selectedChecked(e: any): void {
    this.checkedCashArray = [...e];
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    const params: SearchCommonVO<any> = {
      pageSize: this.tableConfig.pageSize!,
      pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
      filters: this.searchParam
    };
    this.dataService.getLabelTypeList(params).subscribe((data => {
      const {list, total, pageNum} = data;
      this.dataList = [...list];
      this.tableConfig.total = total!;
      this.tableConfig.pageIndex = pageNum!;
      this.tableLoading(false);
    }));
  }

  resetForm(): void {
    this.searchParam = {};
    this.getDataList();
  }

  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  add(): void {
    this.modalService.show({nzTitle: '新增'}).subscribe(({modalValue, status}) => {
      if (status === ModalBtnStatus.Cancel) {
        return;
      }
      this.tableLoading(true);
      this.addEditData(modalValue, 'addLabelType');
    }, error => this.tableLoading(false));
  }

  del(id: number): void {
    this.modalSrv.confirm({
      nzTitle: '确定要删除吗？',
      nzContent: '删除后不可恢复',
      nzOnOk: () => {
        this.tableLoading(true);
        this.dataService.delLabelType([id]).subscribe(() => {
          if (this.dataList.length === 1) {
            this.tableConfig.pageIndex--;
          }
          this.getDataList();
          this.checkedCashArray.splice(this.checkedCashArray.findIndex(item => item.id === id), 1);
        }, error => this.tableLoading(false));
      }
    });
  }

  edit(id: number): void {
    this.dataService.getLabelTypeDetail(id).subscribe(res => {
      this.modalService.show({nzTitle: '编辑'}, res).subscribe(({modalValue, status}) => {
        if (status === ModalBtnStatus.Cancel) {
          return;
        }
        modalValue.id = id;
        this.tableLoading(true);
        this.addEditData(modalValue, 'editLabelType');
      }, error => this.tableLoading(false));
    });
  }

  addEditData(param: FileTypeObj, methodName: 'addLabelType' | 'editLabelType'): void {
    this.dataService[methodName](param).subscribe(() => {
      this.getDataList();
    }, error => this.tableLoading(false));
  }


  ngOnInit(): void {
    this.initTable();
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: false,
      headers: [
        {
          title: '标签类型',
          field: 'typeName',
          width: 100,
        },
        {
          title: '标签类型ID',
          field: 'id',
          width: 100,
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 250,
          fixed: true
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }
}
